package com.whjfxx.terminal.api.server.impl;

import com.whjfxx.terminal.api.param.ActiveParam;
import com.whjfxx.terminal.api.server.ActivateService;
import com.whjfxx.terminal.api.vo.ActivateVo;
import com.whjfxx.terminal.biz.enums.YesNoEnum;
import com.whjfxx.terminal.biz.mapper.PoFuncMapper;
import com.whjfxx.terminal.biz.service.PoAppService;
import com.whjfxx.terminal.biz.service.PoFuncService;
import com.whjfxx.terminal.biz.service.PoTerminalService;
import com.whjfxx.terminal.entity.PoApp;
import com.whjfxx.terminal.entity.PoFunc;
import com.whjfxx.terminal.entity.PoTerminal;
import com.whjfxx.terminal.enums.ActiveTypeEnum;
import com.whjfxx.terminal.enums.CheckCycleEnum;
import com.whjfxx.terminal.exceptions.BizException;
import com.whjfxx.terminal.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@Service
public class ActivateServiceImpl implements ActivateService {

    @Autowired
    PoTerminalService poTerminalService;

    @Autowired
    PoAppService poAppService;

    @Autowired
    PoFuncService poFuncService;

    @Autowired
    PoFuncMapper poFuncMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivateVo activate(ActiveParam activeParam) {
        // 查询序列号
        PoTerminal terminal = poTerminalService.getBySnAndFuncName(activeParam.getTerminal_sn(), activeParam.getFunc_name());
        if (Objects.isNull(terminal)) {
            throw BizException.build("请联系管理员激活终端");
        }
        if (YesNoEnum.NO.status == terminal.getStatus()) {
            throw BizException.build("功能已关闭，请联系管理员");
        }
        // 查询应用名称
        PoApp app =  poAppService.getById(terminal.getAppId());
        if (Objects.isNull(app)) {
            log.error("应用信息不存在[{}]", terminal.getAppId());
            throw BizException.build("功能暂不支持，请联系管理员");
        }
        // 查询功能名称
        PoFunc func = poFuncService.getById(terminal.getFuncId());
        if (Objects.isNull(func)) {
            log.error("功能信息不存在[{}]", terminal.getFuncId());
            throw BizException.build("功能暂不支持，请联系管理员");
        }

        // 是否已经激活
        if (YesNoEnum.YES.status == terminal.getActiveStatus()) {
            if (!ActiveTypeEnum.P.code.equals(terminal.getExpiryType()) && DateUtil.beforeNow(terminal.getExpiryTime())) {
                throw BizException.build("设备已过期，请联系管理员");
            }
            // 直接返回数据
            return getActiveVo(app, func, terminal);
        }


        if (ActiveTypeEnum.P.code.equals(terminal.getExpiryType())) {
            // 更新 设备状态为激活状态
            terminal.setActiveStatus(YesNoEnum.YES.status);
            LocalDateTime activeReqTime = DateUtil.parse_yyyyMMddHHmmss(activeParam.getReq_time());
            terminal.setActiveReqTime(activeReqTime);
            terminal.setActiveType(terminal.getExpiryType());
            terminal.setActiveTime(LocalDateTime.now());
            terminal.setUpdateTime(LocalDateTime.now());
            terminal.setAppVer(activeParam.getApp_ver());
            terminal.setFuncVer(activeParam.getVersion());
            terminal.setTerminal_local(activeParam.getTerminal_local());
            terminal.setTerminalAddress(activeParam.getTerminal_address());
            poTerminalService.updateById(terminal);

            return getActiveVo(app, func, terminal);
        }

        terminal.setActiveStatus(YesNoEnum.YES.status);
        LocalDateTime activeReqTime = DateUtil.parse_yyyyMMddHHmmss(activeParam.getReq_time());
        terminal.setActiveReqTime(activeReqTime);
        terminal.setActiveType(terminal.getExpiryType());
        terminal.setActiveTime(LocalDateTime.now());
        terminal.setUpdateTime(LocalDateTime.now());

        long activeType = Long.parseLong(terminal.getExpiryType());
        terminal.setExpiryTime(activeReqTime.plusMonths(activeType));

        poTerminalService.updateById(terminal);
        return getActiveVo(app, func, terminal);
    }

    @Override
    public String getToken(String appName, String funcName) {
        PoFunc func = poFuncMapper.getByAppNameAndFuncName(appName, funcName);
        if (Objects.isNull(func)) {
            throw BizException.build("token信息错误，请联系管理员");
        }
        return func.getToken();
    }

    public ActivateVo getActiveVo(PoApp app, PoFunc func, PoTerminal terminal) {
        ActivateVo activateVo = new ActivateVo();
        activateVo.setApp_name(app.getAppName());
        activateVo.setFunc_name(func.getFuncName());
        activateVo.setTerminal_sn(terminal.getSn());
        activateVo.setTerminal_type(terminal.getTerminalType());
        if (ActiveTypeEnum.P.code.equals(terminal.getExpiryType())) {
            // 长期有效
            activateVo.setAuth_exp_type("Y");
        } else {
            // 临时有效
            activateVo.setAuth_exp_type("N");
            activateVo.setAuth_exp(terminal.getExpiryType());

            String auth_end = DateUtil.formate_yyyyMMddHHmmss(terminal.getExpiryTime());
            activateVo.setAuth_end(auth_end);
        }
        activateVo.setCheck_cycle(CheckCycleEnum.d.name());
        return activateVo;
    }
}
